package com.un.ebs.core.tenant;

import com.baomidou.mybatisplus.core.parser.ISqlParser;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.tenant.TenantHandler;
import com.baomidou.mybatisplus.extension.plugins.tenant.TenantSqlParser;
import com.un.ebs.core.UserContext;
import com.un.ebs.core.exception.BusinessException;
import com.un.ebs.core.exception.BusinessNotSetUserContent;
import com.un.ebs.core.util.SecurityUtils;
import com.un.ebs.core.util.StringUtils;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.StringValue;
import net.sf.jsqlparser.expression.operators.relational.ExpressionList;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.List;

@Configuration
public class MybatisPlusConfig {

    public static List<String> includeTenantTable = new ArrayList<>();

    /**
     * 多租户属于 SQL 解析部分，依赖 MP 分页插件
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();

        /*
         * 【测试多租户】 SQL 解析处理拦截器<br>
         * 这里固定写成住户 1 实际情况你可以从cookie读取，因此数据看不到 【 麻花藤 】 这条记录（ 注意观察 SQL ）<br>
         */
        List<ISqlParser> sqlParserList = new ArrayList<>();
        TenantSqlParser tenantSqlParser = new TenantParser();
        tenantSqlParser.setTenantHandler(new TenantHandler() {

            /**
             * 2019-8-1
             *
             * https://gitee.com/baomidou/mybatis-plus/issues/IZZ3M
             *
             * tenant_id in (1,2)
             *
             * @return
             */
            @Override
            public Expression getTenantId(boolean where) {
                boolean multipleTenantIds = true;
                try {
                    SecurityUtils.getUserContent();
                } catch (Exception e) {
                    multipleTenantIds = false;
                }

                if (where && multipleTenantIds) {
                    if (StringUtils.isNullOrEmpty(getTenantId()))
                        return null;
                    else
                        return multipleTenantIdCondition();
                } else {
                    return singleTenantIdCondition();
                }
            }

            /**
             * 从当前用户信息中获取租户ID
             * @return
             */
            private String getTenantId() {
                //UserContext userContext = null;
                try {
                    //userContext = SecurityUtils.getUserContent();
                    return SecurityUtils.getTenantId();
                    //return userContext.getTenantId();
                } catch (BusinessNotSetUserContent ex) {
                    return "";
                }
//                if(SecurityUtils.getUserContent()==null){
//                    return null;
//                }
//                else if(StringUtils.isNullOrEmpty(SecurityUtils.getUserContent().getTenantId())) {
//                    return null;
//                }
//                else{
//                    return SecurityUtils.getUserContent().getTenantId();
//                }

            }

            private Expression singleTenantIdCondition() {
                if (StringUtils.isNullOrEmpty(getTenantId())) {
                    throw new BusinessException("当前租户ID不能为空。");
                }
                return new StringValue(getTenantId());
            }

            private Expression multipleTenantIdCondition() {

                final ExpressionList itemsList = new ExpressionList();
                final List<Expression> inValues = new ArrayList<>(1);
                inValues.add(new StringValue(getTenantId()));
                itemsList.setExpressions(inValues);
                return new StringValue(getTenantId());
            }

            @Override
            public String getTenantIdColumn() {
                return "tenant_id";
            }

            @Override
            public boolean doTableFilter(String tableName) {
                if (tableName.equals("v_user_ext") ||
                        tableName.equals("v_user_tenant_ext") ||
                        tableName.equals("v_app_power_ext") ||
                        tableName.equals("v_app_rule_ext") ||
                        tableName.equals("v_app_tenant_ext") ||
                        tableName.equals("v_app_role_power_ext") ||
                        tableName.equals("v_app_role_rule_ext") ||
                        tableName.equals("v_app_user_role_ext") ||
                        tableName.equals("v_configure_value_ext") ||
                        tableName.equals("v_user_power_ext") ||
                        tableName.equals("tb_customer") ||
                        tableName.equals("tb_order_payment") ||
                        tableName.equals("v_personnel_ext")) {
                    return true;
                } else if (tableName.equals("sys_dictionary_value")) {
                    return false;
                } else if (tableName.startsWith("sys_")) {
                    return true;
                } else return !MybatisPlusConfig.includeTenantTable.contains(tableName);
            }
        });

        sqlParserList.add(tenantSqlParser);
        paginationInterceptor.setSqlParserList(sqlParserList);
        return paginationInterceptor;
    }
}
